package agent.client.android;

import jade.android.AndroidHelper;
import jade.android.MicroRuntimeService;
import jade.android.MicroRuntimeServiceBinder;
import jade.android.RuntimeCallback;
import jade.core.MicroRuntime;
import jade.core.Profile;
import jade.util.Logger;
import jade.util.leap.Properties;
import jade.wrapper.AgentController;
import jade.wrapper.ControllerException;
import agent.client.android.agent.AndroidAgent;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity{

	private Logger logger = Logger.getMyLogger(this.getClass().getName());

	private MicroRuntimeServiceBinder microRuntimeServiceBinder;
	private ServiceConnection serviceConnection;
	
	private AgentController agentController;
	
	private EditText username;
	private EditText password;
	
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	    
	    Button button = (Button)findViewById(R.id.button);
	    button.setOnClickListener(buttonListener);
	    
	}
	
	private OnClickListener buttonListener=new OnClickListener() {
		
		public void onClick(View v) {
			
			username = (EditText)findViewById(R.id.username); 
			password = (EditText)findViewById(R.id.password); 
			
			logger.info(" LISTENER: "+username.getText().toString());
			logger.info(" PASSWORD: "+password.getText().toString());
			
			switchActivity();
			startJade(username.getText().toString().replace("@", "#")+"$mobile", password.getText().toString(), MainActivity.this, agentStartupCallback);			
			
			
		}
		
	};
	
	public void switchActivity() {
		
		Intent intent = new Intent(MainActivity.this, HomeActivity.class);
		intent.putExtra("username", username.getText().toString().replace("@", "#")+"$mobile");
		startActivity(intent);
	}
	
//	@Override
//	protected void onPause() {
//		super.onPause();
//logger.info("IN PAUSE");
//		try {
//			
//			if(agentController!=null)
//				agentController.kill();
//			
//			microRuntimeServiceBinder.stopAgentContainer(new RuntimeCallback<Void>() {
//
//				@Override
//				public void onSuccess(Void result) {
//					// TODO Auto-generated method stub
//					logger.info("Successfully stopped of the container...");
//				}
//
//				@Override
//				public void onFailure(Throwable throwable) {
//					// TODO Auto-generated method stub
//					logger.severe("Failed to stopped the container...");
//				}
//				
//				
//			});
//			
//		} catch (StaleProxyException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//		logger.info("Destroy activity!");
//	}
	
	private RuntimeCallback<AgentController> agentStartupCallback = new RuntimeCallback<AgentController>() {
		@Override
		public void onSuccess(AgentController agent) {
			
			agentController = agent;
		}

		@Override
		public void onFailure(Throwable throwable) {
			logger.info("ERROR: Agent not started");
			
			agentController = null;
			
//			myHandler.postError(getString(R.string.msg_nickname_in_use));
		}
	};
	
	private void startJade(final String nickname, final String password, final MainActivity activity, final RuntimeCallback<AgentController> agentStartupCallback) {

		final Properties profile = new Properties();
		profile.setProperty(Profile.MAIN_HOST, "192.168.1.8");
		profile.setProperty(Profile.MAIN_PORT, "1099");
		profile.setProperty(Profile.MAIN, Boolean.FALSE.toString());
		profile.setProperty(Profile.JVM, Profile.ANDROID);

		if (AndroidHelper.isEmulator()) {

			// Emulator: this is needed to work with emulated devices
			profile.setProperty(Profile.LOCAL_HOST, AndroidHelper.LOOPBACK);

		} else {

			profile.setProperty(Profile.LOCAL_HOST,	AndroidHelper.getLocalIPAddress());
		}

		// Emulator: this is not really needed on a real device
		profile.setProperty(Profile.LOCAL_PORT, "2000");

		if (microRuntimeServiceBinder == null) {

			serviceConnection = new ServiceConnection() {

				public void onServiceConnected(ComponentName className,	IBinder service) {

					microRuntimeServiceBinder = (MicroRuntimeServiceBinder) service;
					
					logger.info("Gateway successfully bound to MicroRuntimeService");
					
					startContainer(nickname, password, profile, activity, agentStartupCallback);
				};

				public void onServiceDisconnected(ComponentName className) {
					
					microRuntimeServiceBinder = null;
					logger.info("Gateway unbound from MicroRuntimeService");
				}
			};

			logger.info("Binding Gateway to MicroRuntimeService...");
			bindService(new Intent(getApplicationContext(),	MicroRuntimeService.class), serviceConnection, Context.BIND_AUTO_CREATE);

		} else {

			logger.info("MicroRumtimeGateway already binded to service");
			startContainer(nickname, password, profile, activity, agentStartupCallback);
		}
	}

	private void startContainer(final String nickname, final String password, Properties profile, final MainActivity activity, final RuntimeCallback<AgentController> agentStartupCallback) {

		if (!MicroRuntime.isRunning()) {

			microRuntimeServiceBinder.startAgentContainer(profile, new RuntimeCallback<Void>() {

				@Override
				public void onSuccess(Void thisIsNull) {

					logger.info("Successfully start of the container...");
					startAgent(nickname, password, activity, agentStartupCallback);
				}

				@Override
				public void onFailure(Throwable throwable) {

					logger.severe("Failed to start the container...");
				}
			});

		} else {

			startAgent(nickname, password, activity, agentStartupCallback);
		}
	}

	private void startAgent(final String nickname, final String password, final MainActivity activity, final RuntimeCallback<AgentController> agentStartupCallback) {

		microRuntimeServiceBinder.startAgent(nickname, AndroidAgent.class.getName(), new Object[] { password, getApplicationContext(), activity }, new RuntimeCallback<Void>() {

			@Override
			public void onSuccess(Void thisIsNull) {

				logger.info("Successfully start of the "+ AndroidAgent.class.getName() + "...");

				try {

					agentStartupCallback.onSuccess(MicroRuntime.getAgent(nickname));

				} catch (ControllerException e) {
					// Should never happen
					agentStartupCallback.onFailure(e);
				}
			}

			@Override
			public void onFailure(Throwable throwable) {

				logger.severe("Failed to start the "+ AndroidAgent.class.getName() + "...");
				agentStartupCallback.onFailure(throwable);
			}
		});
	}
}